#include "EyerWASMBlob_OpenEvent.hpp"

#include <emscripten.h>

extern "C"
{
EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_OpenEvent_Open(void *ctx, const char * blobUrl);

EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_OpenEvent_Open_OnSucc(void * ctx, int blobKey, int fileSize)
{
    Eyer::EyerWASMBlob_OpenEvent * event = (Eyer::EyerWASMBlob_OpenEvent *)ctx;
    return event->EyerWASMBlob_OpenEvent_Open_OnSucc(blobKey, fileSize);
}

EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_OpenEvent_Open_OnFail(void * ctx)
{
    Eyer::EyerWASMBlob_OpenEvent * event = (Eyer::EyerWASMBlob_OpenEvent *)ctx;
    return event->EyerWASMBlob_OpenEvent_Open_OnFail();
}
}

namespace Eyer
{
    EyerWASMBlob_OpenEvent::EyerWASMBlob_OpenEvent(const std::string & blobUrl)
    {
        m_blobUrl = blobUrl;
    }

    EyerWASMBlob_OpenEvent::~EyerWASMBlob_OpenEvent()
    {

    }

    int EyerWASMBlob_OpenEvent::Run()
    {
        EyerWASMBlob_OpenEvent_Open(this, m_blobUrl.c_str());
        return 0;
    }

    int EyerWASMBlob_OpenEvent::EyerWASMBlob_OpenEvent_Open_OnSucc(int blobKey, int64_t fileSize)
    {
        std::unique_lock<std::mutex> lck(mtx);
        m_blobKey = blobKey;
        m_fileSize = fileSize;
        isFinished = true;
        isSucced = true;
        cond.notify_all();
        return 0;
    }

    int EyerWASMBlob_OpenEvent::EyerWASMBlob_OpenEvent_Open_OnFail()
    {
        std::unique_lock<std::mutex> lck(mtx);
        isFinished = true;
        isSucced = false;
        cond.notify_all();
        return 0;
    }

    int EyerWASMBlob_OpenEvent::GetBlobKey()
    {
        return m_blobKey;
    }

    int64_t EyerWASMBlob_OpenEvent::GetFileSize()
    {
        return m_fileSize;
    }
}